/* @(#)
 *
 * Project:  jekun-shop
 *
 * Modify Information:
 * =============================================================================
 *   Author           Date           Description
 *   ------------     ----------     --------------------------------------------
 *   Roger.Luo        2014年5月5日        first release
 *
 *
 * Copyright Notice:
 * =============================================================================
 *       Copyright 2014 FANKE Software, Inc. All rights reserved.
 *
 *       This software is the confidential and proprietary information of
 *       GUANGZHOU FANKE INTERNET TECHNOLOGY CO.,LTD ("Confidential Information").
 *       You shall not disclose such Confidential Information and shall use it
 *       only in accordance with the terms of the license agreement you entered
 *       into with FANKE.
 *
 * Warning:
 * =============================================================================
 *
 */
package cn.jekun.shop.app.action;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Types;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.Constants.MAINFRAME_TYPE;
import cn.jekun.component.core.Constants.TXN_STATE;
import cn.jekun.component.core.DateUtils;
import cn.jekun.component.core.bean.gen.ErpOrders;
import cn.jekun.component.core.bean.gen.ErpTxnSeq;
import cn.jekun.component.core.service.gen.ErpOrdersService;
import cn.jekun.component.core.service.gen.ErpTxnSeqService;
import cn.jekun.component.pay.base.BasePay;
import cn.jekun.component.pay.common.utils.WechatPayTools;
import cn.jekun.component.pay.webpay.Alipay;
import cn.jekun.component.shop.service.OrderService;
import cn.jekun.component.shop.service.ThirdBusinessService;
import cn.jekun.shop.web.service.UnionPayService;

import com.EasyLink.OpenVendorV34.NetTran;

/**
 * 
 * @author Roger
 *
 */
@SuppressWarnings("serial")
public class WebPayAction extends AppBaseAction {
	
	@Resource(name=ErpOrdersService.BEAN_NAME)
	ErpOrdersService orpOrdersService;
	@Resource(name=UnionPayService.BEAN_NAME)
	UnionPayService unionPayService;	
	@Resource(name=OrderService.BEAN_NAME)
	OrderService orderService;
	@Resource(name=ErpTxnSeqService.BEAN_NAME)
	ErpTxnSeqService erpTxnSeqService;
	@Resource(name=ThirdBusinessService.BEAN_NAME)
	ThirdBusinessService thirdBusinessService;
	@Resource(name=cn.jekun.shop.common.service.OrderService.BEAN_NAME)
	cn.jekun.shop.common.service.OrderService OrderService1;
	//记录日志信息
	private static Logger logger=Logger.getLogger(WebPayAction.class);
	
/*	*//**
	 * 微信支付 接口
	 * @param orderId 订单编号
	 * @param orderTime 下单时间
	 * @param orderAmount 订单支付金额 
	 * @param channelCode 渠道代码 ，03:IOS，04:android，05：终端
	 * @return
	 *//*
    public String payByWXPay(){
    	
    	logger.info("********************WebPayAction payByWXPay Begin********************");
    	
    	JSONObject jsonObject = new JSONObject();
    	String terminalId=request.getParameter("terminalId");
        String userId=request.getParameter("userId");
        String orderId=request.getParameter("orderId");
        String orderTime=request.getParameter("orderTime");
        String orderAmount=request.getParameter("orderAmount");
        String channelCode=request.getParameter("channelCode");
        try{
        	//先根据订单号查询订单信息是否存在，然后再保存交易信息
        	Map formTxnMap = new HashMap();
    		formTxnMap.put(ErpOrders.COL_ORDER_ID, orderId);
    		SqlUtis.prepareSql(formTxnMap,SqlUtis.getSQL(formTxnMap, "a."+ ErpOrders.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ));
    		ErpOrders erpOrder = orpOrdersService.one(formTxnMap);
    		
    		if(erpOrder==null){
    			jsonObject.put("prepayid", "");
                jsonObject.put("orderId", orderId);
                jsonObject.put("code", "04");
                jsonObject.put("message", "订单不存在，请重试");
                logger.info("根据订单号"+orderId+"查询订单信息不存在，请重试！");
                return this.writeJson(jsonObject);
    		}
    		if (!this.orderService.allowPay(erpOrder)) {//是否允许支付
    			jsonObject.put("tn", "");
                jsonObject.put("orderId", orderId);
                jsonObject.put("code", "04");
                jsonObject.put("message", "订单不允许支付");
                logger.info("根据订单号不允许支付!");
                return this.writeJson(jsonObject);
			}
        	//开始记录交易流水信息
        	String returnId=unionPayService.saveTxnInfo(orderId, Constants.TRANS_TYPE.GO_PAY, Constants.ONLINE_PAYMENT.WX_PAY, Constants.MAINFRAME_TYPE.FRONT_PAY, "", TXN_STATE.TXN_O0,"","",channelCode);
        	BasePay wxPay=BasePay.CreateNewWebPay("04", orderId, orderAmount);
        	wxPay.setRequest(request);
        	wxPay.setResponse(response);
    		jsonObject=wxPay.Pay();
    		
    		String prepayid=jsonObject.getString("prepayid");
    		String resCode=jsonObject.getString("code");
    		String respMsg=jsonObject.getString("message");
    		//String transType=jsonObject.getString("transType");
        	
    		//开始记录返回的交易流水信息(prepayid长度超过了32)
        	//String rreturnId=unionPayService.saveTxnInfo(orderId, Constants.TRANS_TYPE.GO_PAY, Constants.ONLINE_PAYMENT.WX_PAY, Constants.MAINFRAME_TYPE.FRONT_PAY,prepayid, TXN_STATE.TXN_O2,resCode,respMsg,channelCode);
        	logger.info("********************WebPayAction payByWXPay End********************");
            return this.writeJson(jsonObject);
        
        }catch(Exception exc){
        	
        	logger.info(exc.getMessage());;
			jsonObject.put("code", "0");
			jsonObject.put("message", "支付失败"+exc.getMessage());
			return this.writeJson(jsonObject);
        }
    }*/
	/**
	 * 微信支付 接口
	 * @param orderId 订单编号
	 * @param orderTime 下单时间
	 * @param orderAmount 订单支付金额 
	 * @param channelCode 渠道代码 ，03:IOS，04:android，05：终端
	 * @return
	 */
    public String payByWXPay(){
    	
    	logger.info("********************WebPayAction payByWXPay Begin********************");
    	
    	JSONObject jsonObject = new JSONObject();
    	String terminalId=request.getParameter("terminalId");
        String userId=request.getParameter("userId");
        String orderId=request.getParameter("orderId");
        String orderTime=request.getParameter("orderTime");
        String orderAmount=request.getParameter("orderAmount");
        String channelCode = request.getParameter("channelCode");
        try{
        	//先根据订单号查询订单信息是否存在，然后再保存交易信息
        	Map formTxnMap = new HashMap();
    		formTxnMap.put(ErpOrders.COL_ORDER_ID, orderId);
    		SqlUtis.prepareSql(formTxnMap,SqlUtis.getSQL(formTxnMap, "a."+ ErpOrders.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ));
    		ErpOrders erpOrder = orpOrdersService.one(formTxnMap);
    		
    		if(erpOrder==null){
    			jsonObject.put("prepayid", "");
                jsonObject.put("orderId", orderId);
                jsonObject.put("code", "04");
                jsonObject.put("message", "订单不存在，请重试");
                logger.info("根据订单号"+orderId+"查询订单信息不存在，请重试！");
                return this.writeJson(jsonObject);
    		}
    		if (!this.orderService.allowPay(erpOrder)) {//是否允许支付
    			jsonObject.put("tn", "");
                jsonObject.put("orderId", orderId);
                jsonObject.put("code", "04");
                jsonObject.put("message", "订单不允许支付");
                logger.info("根据订单号不允许支付!");
                return this.writeJson(jsonObject);
			}
    		//支付
    		String couponId=request.getParameter("couponId");//优惠券代码
    		String balance=request.getParameter("balance");//余额支付
    		String password=request.getParameter("password");//md5支付密码
    		try{
	    		boolean isOk = this.orderService.otherPay(couponId, balance, userId, orderAmount, erpOrder, Constants.ONLINE_PAYMENT.WX_PAY, "", "",password);
	    		if (isOk) {//支付成功
//	    			jsonObject.put("tn", "");
//	                jsonObject.put("orderId", orderId);
	    			jsonObject.put("code", "1");
	    			jsonObject.put("payed", "1");//已经支付完成，不需要再支付
	    			jsonObject.put("message", "支付成功");
	    			jsonObject.put("appid", "");
	    			jsonObject.put("partnerid", "");
	    			jsonObject.put("prepayid", "");
	    			jsonObject.put("noncestr", "");
	    			jsonObject.put("package", "");
	    			jsonObject.put("timestamp", "");
	    			jsonObject.put("sign", "");
	    			jsonObject.put("orderId", orderId);
	    			return this.writeJson(jsonObject);
				}
    		}catch(BusinessException e){
//    			jsonObject.put("tn", "");
//                jsonObject.put("orderId", orderId);
    			jsonObject.put("code", "0");//支付失败
    			jsonObject.put("payed", "0");
    			jsonObject.put("message", e.getMessage());
    			jsonObject.put("appid", "");
    			jsonObject.put("partnerid", "");
    			jsonObject.put("prepayid", "");
    			jsonObject.put("noncestr", "");
    			jsonObject.put("package", "");
    			jsonObject.put("timestamp", "");
    			jsonObject.put("sign", "");
    			jsonObject.put("orderId", orderId);
    			
    			return this.writeJson(jsonObject);
    		}
        	//开始记录交易流水信息
        	String returnId=unionPayService.saveTxnInfo(orderId, Constants.TRANS_TYPE.GO_PAY, Constants.ONLINE_PAYMENT.WX_PAY, Constants.MAINFRAME_TYPE.FRONT_PAY, "", TXN_STATE.TXN_O0,"","",channelCode);
        	BasePay wxPay=BasePay.CreateNewWebPay("04", orderId, orderAmount);
        	wxPay.setRequest(request);
        	wxPay.setResponse(response);
    		jsonObject=wxPay.Pay();
    		
    		String prepayid=jsonObject.getString("prepayid");
    		String resCode=jsonObject.getString("code");
    		String respMsg=jsonObject.getString("message");
        	
    		//开始记录返回的交易流水信息
//        	String rreturnId=unionPayService.saveTxnInfo(orderId, Constants.TRANS_TYPE.GO_PAY, Constants.ONLINE_PAYMENT.WX_PAY, Constants.MAINFRAME_TYPE.FRONT_PAY,prepayid, TXN_STATE.TXN_O2,resCode,respMsg,channelCode);
        	logger.info("********************WebPayAction payByWXPay End********************");
            return this.writeJson(jsonObject);
        
        }catch(Exception exc){
        	
        	logger.info(exc.getMessage());;
			jsonObject.put("code", "0");
			jsonObject.put("message", "支付失败"+exc.getMessage());
			return this.writeJson(jsonObject);
        }
    }
    
    /**
     * alipay支付
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public String payByAlipay(){
    	logger.info("********************WebPayAction payByAlipay Begin********************");
    	
    	JSONObject jsonObject = new JSONObject();
        String userId=request.getParameter("userId");
        String orderId=request.getParameter("orderId");
        String orderTime=request.getParameter("orderTime");
        String orderAmount=request.getParameter("orderAmount");
        String channelCode=request.getParameter("channelCode");
        String loginSign=getLoginSign();
        this.validateSign(loginSign,userId,orderId,orderTime,orderAmount,channelCode);
        this.validateLoginApp();//验证是否登录
        
        try{
        	//先根据订单号查询订单信息是否存在，然后再保存交易信息
        	Map formTxnMap = new HashMap();
    		formTxnMap.put(ErpOrders.COL_ORDER_ID, orderId);
    		SqlUtis.prepareSql(formTxnMap,SqlUtis.getSQL(formTxnMap, "a."+ ErpOrders.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ));
    		ErpOrders erpOrder = orpOrdersService.one(formTxnMap);
    		
    		if(erpOrder==null){
    			jsonObject.put("tn", "");
                jsonObject.put("orderId", orderId);
                jsonObject.put("code", "04");
                jsonObject.put("message", "订单不存在，请重试");
                logger.info("根据订单号"+orderId+"查询订单信息不存在，请重试！");
                return this.writeJson(jsonObject);
    		}
    		if (!this.orderService.allowPay(erpOrder)) {//是否允许支付
    			jsonObject.put("tn", "");
                jsonObject.put("orderId", orderId);
                jsonObject.put("code", "04");
                jsonObject.put("message", "订单不允许支付");
                logger.info("根据订单号不允许支付!");
                return this.writeJson(jsonObject);
			}
    		//支付
    		String couponId=request.getParameter("couponId");//优惠券代码
    		String balance=request.getParameter("balance");//余额支付
    		String password=request.getParameter("password");//md5支付密码
    		try{
	    		boolean isOk = this.orderService.otherPay(couponId, balance, userId, orderAmount, erpOrder, Constants.ONLINE_PAYMENT.ALIPAY, "", "",password);
	    		if (isOk) {//支付成功
	    			jsonObject.put("tn", "");
	                jsonObject.put("orderId", orderId);
	    			jsonObject.put("code", "1");
	    			jsonObject.put("payed", "1");//已经支付完成，不需要再支付
	    			jsonObject.put("message", "支付成功");
	    			return this.writeJson(jsonObject);
				}
    		}catch(BusinessException e){
    			jsonObject.put("tn", "");
                jsonObject.put("orderId", orderId);
    			jsonObject.put("code", "0");
    			jsonObject.put("payed", "0");//支付失败
    			jsonObject.put("message", e.getMessage());
    			
    			return this.writeJson(jsonObject);
    		}
        	//开始记录交易流水信息
        	unionPayService.saveTxnInfo(orderId, Constants.TRANS_TYPE.GO_PAY, Constants.ONLINE_PAYMENT.ALIPAY, Constants.MAINFRAME_TYPE.FRONT_PAY, "", TXN_STATE.TXN_O0,"","",channelCode);
        	BasePay alipay=BasePay.CreateNewWebPay("06", orderId, orderAmount);
    		jsonObject = alipay.Pay();
    		
    		String tn=jsonObject.getString("tn");
    		jsonObject.put("payed", "0");//没有支付完成，需要再调用银联
        	logger.info("********************WebPayAction payByAlipay End********************");
            
        	jsonObject.put("tn", tn);//没有支付完成，需要再调用银联
        	
        	return this.writeJson(jsonObject);
        
        }catch(Exception exc){
        	logger.info(exc.getMessage());;
			jsonObject.put("code", "0");
			jsonObject.put("message", "组装支付信息失败");
			return this.writeJson(jsonObject);
        }
    }
    
    
    /**
     * 微信手机支付订单推送，后台返回报文
     */
   /* public void notifyWXPayResult(){
    	
    	logger.info("********************WebPayAction notifyWXPayResult Begin********************");
    	logger.info("********************WebPayAction 开始接收微信支付后台返回报文 Begin********************");
    	JSONObject jsonObject=new JSONObject();
    	String userId="system";
    	
    	BasePay wxPay=BasePay.CreateNewWebPay("04", "", "");
    	wxPay.setRequest(request);
    	wxPay.setResponse(response);
    	//获取订单返回参数信息
		jsonObject=wxPay.NotifyBackInfo();
		
		String code=jsonObject.getString("code");
		String message=jsonObject.getString("message");
		
		
		jsonObject.put("out_trade_no", m.get("out_trade_no").toString());
		jsonObject.put("transaction_id", m.get("transaction_id").toString());
		jsonObject.put("total_fee",m.get("total_fee").toString());
		jsonObject.put("appid",m.get("appid").toString());
		jsonObject.put("bank_type",m.get("bank_type").toString());
		jsonObject.put("fee_type",m.get("fee_type").toString());
		jsonObject.put("is_subscribe",m.get("is_subscribe").toString());
		jsonObject.put("trade_type",m.get("trade_type").toString());
		jsonObject.put("time_end",m.get("time_end").toString());
		
		if(code.equals("1")){
			String orderID = jsonObject.getString("out_trade_no");// 订单号
			String result_code = jsonObject.getString("result_code");// 交易状态
			String transaction_id = jsonObject.getString("transaction_id");//微信支付订单号
			// 查询订单是否已支付成功
			Map formTxnMap = new HashMap();
			formTxnMap.put(ErpOrders.COL_ORDER_ID, orderID);
			SqlUtis.prepareSql(formTxnMap, SqlUtis.getSQL(formTxnMap, "a."
					+ ErpOrders.COL_ORDER_ID, Types.VARCHAR, SqlUtis.EQ));
			ErpOrders orders = orpOrdersService.one(formTxnMap);
			// 原始交易为订单支付
			if(result_code.equals("SUCCESS")) {//TRADE_SUCCESS 支付成功
				
				Map formQueryTxnMap = new HashMap();
				formQueryTxnMap.put(ErpTxnSeq.COL_ORDER_ID, orderID);
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_STATE, "2");
				formQueryTxnMap.put(ErpTxnSeq.COL_TRN_TYPE,MAINFRAME_TYPE.BACK_PAY);// 只有前台返回的报文中才有记录该支付流水号
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_TYPE, "00");// 只有查询交易才会返回可用于退货的支付流水号

				SqlUtis.prepareSql(formQueryTxnMap, 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_ORDER_ID,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_STATE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TRN_TYPE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_TYPE,Types.VARCHAR, SqlUtis.EQ));

				ErpTxnSeq txnOldSeq = erpTxnSeqService.one(formQueryTxnMap);

				// 只有在没有更新交易流水的情况下 才记录，保证交易流水的唯一
				if (txnOldSeq == null|| StringUtils.isEmpty(txnOldSeq.getExtTxnSeqId())) {
					try {
						
					unionPayService.saveTxnInfo(orderID,
							Constants.TRANS_TYPE.GO_PAY,
							Constants.ONLINE_PAYMENT.WX_PAY,
							Constants.MAINFRAME_TYPE.BACK_PAY, 
							transaction_id,
							Constants.TXN_STATE.TXN_O2, 
							"0000", 
							result_code,
							Constants.PAY_CHANNEL.PAY_WAP);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (orders.getOrderStatusId().equals(Constants.ERP_ORDER_STATUS.ORDER)) {// 表明订单已经支付成功了
					logger.info("********************TransactionAction notifyWXPayResult 支付后台通知，订单状态已更新，不处理********************");
				} else {
					
					//第三方支付成功后台通知
						orderService.payConfirmOrder(userId, orderID,Constants.ONLINE_PAYMENT.WX_PAY, transaction_id,Constants.PAY_CHANNEL.PAY_WAP);// 保存银联返回的订单支付号，后续退货及撤消需要用到
						thirdBusinessService.callThirdService(orderID, userId);
						unionPayService.saveTxnInfo(orderID,
								Constants.TRANS_TYPE.GO_PAY,
								Constants.ONLINE_PAYMENT.WX_PAY,
								Constants.MAINFRAME_TYPE.BACK_PAY, transaction_id,
								Constants.TXN_STATE.TXN_O1, "0000", result_code,
								Constants.PAY_CHANNEL.PAY_WAP);
				}
			}
		}else{
			logger.info("********************WebPayAction notifyWXPayResult 微信支付后台通知消息处理失败，"+message+"********************");
		}
    	
    	logger.info("********************WebPayAction notifyWXPayResult end********************");
    }*/
    
    
    
    /**
     * 微信手机支付订单推送，后台返回报文
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public String notifyWXPayResult(){
    	
    	logger.info("********************WebPayAction notifyWXPayResult Begin********************");
    	logger.info("********************WebPayAction 开始接收微信支付后台返回报文 Begin********************");
    	JSONObject jsonObject=new JSONObject();
    	String userId="system";
    	String xmlrequest = "";
		try {
			xmlrequest = IOUtils.toString(this.request.getInputStream());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
    	logger.info("微信支付返回的xml="+xmlrequest);
    	
		// 获取微信POST过来反馈信息
		Map<String, String> params = WechatPayTools.getMapFromXML(xmlrequest);
    	BasePay wechatAppPay=BasePay.CreateNewWebPay("04", "", "");
    	wechatAppPay.setParams(params); 
    	//获取订单返回参数信息
		jsonObject=wechatAppPay.NotifyBackInfo();
		
		String code=jsonObject.getString("code");
		String message=jsonObject.getString("message");
		
		//微信支付返回信息验证成功与否
		if (code.equals("1")) {
			String return_code = jsonObject.getString("return_code");
			String orderID = jsonObject.getString("out_trade_no");// 订单号
			String total_fee = jsonObject.getString("total_fee");// 交易金额
			String trade_status = jsonObject.getString("result_code");// 交易状态
			String gmt_create = jsonObject.getString("time_end");// 交易日期
			String trade_no = jsonObject.getString("transaction_id");//支付宝交易号
			// 查询订单是否已支付成功
			Map formTxnMap = new HashMap();
			formTxnMap.put(ErpOrders.COL_ORDER_ID, orderID);
			SqlUtis.prepareSql(formTxnMap, SqlUtis.getSQL(formTxnMap, "a."
					+ ErpOrders.COL_ORDER_ID, Types.VARCHAR, SqlUtis.EQ));
			ErpOrders orders = orpOrdersService.one(formTxnMap);
			if (trade_status.equals("SUCCESS") && return_code.equals("SUCCESS")) {//TRADE_SUCCESS 支付成功
				logger.info("微信支付成功"+params.toString());
				
				Map formQueryTxnMap = new HashMap();
				formQueryTxnMap.put(ErpTxnSeq.COL_ORDER_ID, orderID);
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_STATE, "2");
				formQueryTxnMap.put(ErpTxnSeq.COL_TRN_TYPE,MAINFRAME_TYPE.BACK_PAY);// 只有前台返回的报文中才有记录该支付流水号
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_TYPE, "00");// 只有查询交易才会返回可用于退货的支付流水号

				SqlUtis.prepareSql(formQueryTxnMap, 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_ORDER_ID,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_STATE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TRN_TYPE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_TYPE,Types.VARCHAR, SqlUtis.EQ));

				ErpTxnSeq txnOldSeq = erpTxnSeqService.one(formQueryTxnMap);

				// 只有在没有更新交易流水的情况下 才记录，保证交易流水的唯一
				if (txnOldSeq == null|| StringUtils.isEmpty(txnOldSeq.getExtTxnSeqId())) {
					try {
						
					unionPayService.saveTxnInfo(orderID,
							Constants.TRANS_TYPE.GO_PAY,
							Constants.ONLINE_PAYMENT.WX_PAY,
							Constants.MAINFRAME_TYPE.BACK_PAY, 
							trade_no,
							Constants.TXN_STATE.TXN_O2, 
							"0000", 
							trade_status,
							Constants.PAY_CHANNEL.PAY_IOS);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (orders.getOrderStatusId().equals(Constants.ERP_ORDER_STATUS.ORDER)) {// 表明订单已经支付成功了
					logger.info("********************WebPayAction notifyWXPayResult 微信支付后台通知，订单状态已更新，不处理********************");
				} else {
					try {
						response.setHeader("Cache-Control", "no-cache");
						response.setHeader("Expires", "0");
						response.setHeader("Pragma", "No-cache");
						
						response.setContentType("text/xml;charset=UTF-8");
						
						String xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml> ";
						response.getWriter().write(xml);
						response.getWriter().flush();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
						orderService.payConfirmOrder(userId, orderID,Constants.ONLINE_PAYMENT.WX_PAY, trade_no,Constants.PAY_CHANNEL.PAY_IOS);// 保存银联返回的订单支付号，后续退货及撤消需要用到
//						thirdBusinessService.callThirdService(orderID, userId);
						// 支付成功后推送
						OrderService1.pushOrderByPayNo(orderID);
						unionPayService.saveTxnInfo(orderID,
								Constants.TRANS_TYPE.GO_PAY,
								Constants.ONLINE_PAYMENT.WX_PAY,
								Constants.MAINFRAME_TYPE.BACK_PAY, trade_no,
								Constants.TXN_STATE.TXN_O1, "0000", trade_status,
								Constants.PAY_CHANNEL.PAY_IOS);
				}
			}
		} else {
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Expires", "0");
			response.setHeader("Pragma", "No-cache");
			
			response.setContentType("text/xml;charset=UTF-8");
			
			String xml = "<xml><return_code><![CDATA[FAIL]]></return_code></xml> ";
			try {
				response.getWriter().write(xml);
				response.getWriter().flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			logger.info("********************WebPayAction notifyWXPayResult 微信支付后台通知消息处理失败，"
					+ message + "********************");
		}
		return null;
    }
    
	/**
	 * 获取银联支付TN号
	 * @param orderId 订单编号
	 * @param orderTime 下单时间
	 * @param orderAmount 订单支付金额 
	 * @param channelCode 渠道代码 ，03:IOS，04:android，05：终端
	 * @return
	 */
    public String getUnionPayTNCode(){
    	
    	logger.info("********************WebPayAction getUnionPayTNCode Begin********************");
    	JSONObject jsonObject = new JSONObject();
        //InputStream is;
        String userId=request.getParameter("userId");
        String orderId=request.getParameter("orderId");
        String orderTime=request.getParameter("orderTime");
        String orderAmount=request.getParameter("orderAmount");
        String channelCode=request.getParameter("channelCode");
        String loginSign=getLoginSign();
        logger.info("getUnionPayTNCode getUnionPayTNCode"+loginSign);
        this.validateSign(loginSign,userId,orderId,orderTime,orderAmount,channelCode);
        this.validateLoginApp();//验证是否登录
        
        try{
        	//先根据订单号查询订单信息是否存在，然后再保存交易信息
        	Map formTxnMap = new HashMap();
    		formTxnMap.put(ErpOrders.COL_ORDER_ID, orderId);
    		SqlUtis.prepareSql(formTxnMap,SqlUtis.getSQL(formTxnMap, "a."+ ErpOrders.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ));
    		ErpOrders erpOrder = orpOrdersService.one(formTxnMap);
    		
    		if(erpOrder==null){
    			jsonObject.put("tn", "");
                jsonObject.put("orderId", orderId);
                jsonObject.put("code", "04");
                jsonObject.put("message", "订单不存在，请重试");
                logger.info("根据订单号"+orderId+"查询订单信息不存在，请重试！");
                return this.writeJson(jsonObject);
    		}
    		if (!this.orderService.allowPay(erpOrder)) {//是否允许支付
    			jsonObject.put("tn", "");
                jsonObject.put("orderId", orderId);
                jsonObject.put("code", "04");
                jsonObject.put("message", "订单不允许支付");
                logger.info("根据订单号不允许支付!");
                return this.writeJson(jsonObject);
			}
    		//支付
    		String couponId=request.getParameter("couponId");//优惠券代码
    		String balance=request.getParameter("balance");//余额支付
    		String password=request.getParameter("password");//md5支付密码
    		try{
	    		boolean isOk = this.orderService.otherPay(couponId, balance, userId, orderAmount, erpOrder, Constants.ONLINE_PAYMENT.UNION_PAY, "", "",password);
	    		if (isOk) {//支付成功
	    			jsonObject.put("tn", "");
	                jsonObject.put("orderId", orderId);
	    			jsonObject.put("code", "1");
	    			jsonObject.put("payed", "1");//已经支付完成，不需要再支付
	    			jsonObject.put("message", "支付成功");
	    			return this.writeJson(jsonObject);
				}
    		}catch(BusinessException e){
    			jsonObject.put("tn", "");
                jsonObject.put("orderId", orderId);
    			jsonObject.put("code", "0");
    			jsonObject.put("payed", "0");//支付失败
    			jsonObject.put("message", e.getMessage());
    			
    			return this.writeJson(jsonObject);
    		}
        	//开始记录交易流水信息
        	String returnId=unionPayService.saveTxnInfo(orderId, Constants.TRANS_TYPE.GO_PAY, Constants.ONLINE_PAYMENT.UNION_PAY, Constants.MAINFRAME_TYPE.FRONT_PAY, "", TXN_STATE.TXN_O0,"","",channelCode);
        	BasePay unionPay=BasePay.CreateNewWebPay("02", orderId, orderAmount);
    		jsonObject=unionPay.GetTNCode();
    		
    		String tn=jsonObject.getString("tn");
    		String resCode=jsonObject.getString("respCode");
    		String respMsg=jsonObject.getString("message");
    		String transType=jsonObject.getString("transType");
        	
    		//开始记录返回的交易流水信息
        	String rreturnId=unionPayService.saveTxnInfo(orderId, Constants.TRANS_TYPE.GO_PAY, Constants.ONLINE_PAYMENT.UNION_PAY, Constants.MAINFRAME_TYPE.FRONT_PAY,tn, TXN_STATE.TXN_O2,resCode,respMsg,channelCode);
        	logger.info("********************WebPayAction getUnionPayTNCode End********************");
            
        	jsonObject.put("payed", "0");//没有支付完成，需要再调用银联
        	return this.writeJson(jsonObject);
        
        }catch(Exception exc){
        	
        	logger.info(exc.getMessage());;
			jsonObject.put("code", "0");
			jsonObject.put("message", "获取TN码失败");
			return this.writeJson(jsonObject);
        }
    }
    /**
     * alipay后台通知返回结果
     */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String notifyAlipayResult() {
		logger.info("********************WebPayAction notifyAlipayResult Begin********************");
		JSONObject jsonObject = new JSONObject();
		String userId = "system";

		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		BasePay alipay =  BasePay.CreateNewWebPay("06", "", "");
		alipay.setParams(params);
		// 获取订单返回参数信息
		jsonObject = alipay.NotifyBackAppInfo();

		String code = jsonObject.getString("code");
		String message = jsonObject.getString("message");
		
		//alipay返回信息验证成功与否
		if (code.equals("1")) {
			String orderID = jsonObject.getString("out_trade_no");// 订单号
			String total_fee = jsonObject.getString("total_fee");// 交易金额
			String trade_status = jsonObject.getString("trade_status");// 交易状态
			String gmt_create = jsonObject.getString("gmt_create");// 交易日期
			String trade_no = jsonObject.getString("trade_no");//支付宝交易号
			// 查询订单是否已支付成功
			Map formTxnMap = new HashMap();
			formTxnMap.put(ErpOrders.COL_ORDER_ID, orderID);
			SqlUtis.prepareSql(formTxnMap, SqlUtis.getSQL(formTxnMap, "a."
					+ ErpOrders.COL_ORDER_ID, Types.VARCHAR, SqlUtis.EQ));
			ErpOrders orders = orpOrdersService.one(formTxnMap);
			// 原始交易为订单支付
			if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.WAIT_BUYER_PAY)//WAIT_BUYER_PAY 交易创建
					||trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_FINISHED)//TRADE_FINISHED 交易成功
					) {
				if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.WAIT_BUYER_PAY)) {
					logger.info("支付宝交易创建"+params.toString());
				}else if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_FINISHED)){
					logger.info("支付宝交易成功"+params.toString());
				}
				try {
					response.setHeader("Cache-Control", "no-cache");
					response.setHeader("Expires", "0");
					response.setHeader("Pragma", "No-cache");
					
					response.setContentType("text/html;charset=UTF-8");
					
					response.getWriter().write("success");
					response.getWriter().flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else if (trade_status.equals(Constants.ALIPAY_TRANS_STATUS.TRADE_SUCCESS)) {//TRADE_SUCCESS 支付成功
				logger.info("支付宝支付成功"+params.toString());
				
				Map formQueryTxnMap = new HashMap();
				formQueryTxnMap.put(ErpTxnSeq.COL_ORDER_ID, orderID);
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_STATE, "2");
				formQueryTxnMap.put(ErpTxnSeq.COL_TRN_TYPE,MAINFRAME_TYPE.BACK_PAY);// 只有前台返回的报文中才有记录该支付流水号
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_TYPE, "00");// 只有查询交易才会返回可用于退货的支付流水号

				SqlUtis.prepareSql(formQueryTxnMap, 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_ORDER_ID,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_STATE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TRN_TYPE,Types.VARCHAR, SqlUtis.EQ), 
						SqlUtis.getSQL(formQueryTxnMap, "a." + ErpTxnSeq.COL_TXN_TYPE,Types.VARCHAR, SqlUtis.EQ));

				ErpTxnSeq txnOldSeq = erpTxnSeqService.one(formQueryTxnMap);

				// 只有在没有更新交易流水的情况下 才记录，保证交易流水的唯一
				if (txnOldSeq == null|| StringUtils.isEmpty(txnOldSeq.getExtTxnSeqId())) {
					try {
						
					unionPayService.saveTxnInfo(orderID,
							Constants.TRANS_TYPE.GO_PAY,
							Constants.ONLINE_PAYMENT.ALIPAY,
							Constants.MAINFRAME_TYPE.BACK_PAY, 
							trade_no,
							Constants.TXN_STATE.TXN_O2, 
							"0000", 
							trade_status,
							Constants.PAY_CHANNEL.PAY_IOS);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (orders.getOrderStatusId().equals(Constants.ERP_ORDER_STATUS.ORDER)) {// 表明订单已经支付成功了
					logger.info("********************WebPayAction notifyAlipayResult alipay支付后台通知，订单状态已更新，不处理********************");
				} else {
					try {
						response.setHeader("Cache-Control", "no-cache");
						response.setHeader("Expires", "0");
						response.setHeader("Pragma", "No-cache");
						
						response.setContentType("text/html;charset=UTF-8");
						
						response.getWriter().write("success");
						response.getWriter().flush();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
						orderService.payConfirmOrder(userId, orderID,Constants.ONLINE_PAYMENT.ALIPAY, trade_no,Constants.PAY_CHANNEL.PAY_IOS);// 保存银联返回的订单支付号，后续退货及撤消需要用到
						thirdBusinessService.callThirdService(orderID, userId);
						// 支付成功后推送
						OrderService1.pushOrderByPayNo(orderID);
						unionPayService.saveTxnInfo(orderID,
								Constants.TRANS_TYPE.GO_PAY,
								Constants.ONLINE_PAYMENT.ALIPAY,
								Constants.MAINFRAME_TYPE.BACK_PAY, trade_no,
								Constants.TXN_STATE.TXN_O1, "0000", trade_status,
								Constants.PAY_CHANNEL.PAY_IOS);
				}
			}
		} else {
			logger.info("********************WebPayAction notifyAlipayResult alipay支付后台通知消息处理失败，"
					+ message + "********************");
		}
		return null;
	}
    
    /**
     * 银联手机支付订单推送，后台返回报文
     */
    public void notifyWebPayResult(){
    	
    	logger.info("********************WebPayAction notifyWebPayResult Begin********************");
    	logger.info("********************WebPayAction 开始接收银联手机支付后台返回报文 Begin********************");
    	JSONObject jsonObject=new JSONObject();
    	String userId="system";
    	
    	//获取银联POST过来异步通知信息
    	String txn_State="2";
    	Map<String,String> params = new HashMap<String,String>();
    	Map requestParams = request.getParameterMap();
    	logger.info("接收到的原始报文信息："+requestParams.toString());
    	for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
    		String name = (String) iter.next();
    		String[] values = (String[]) requestParams.get(name);
    		String valueStr = "";
    		for (int i = 0; i < values.length; i++) {
    			valueStr = (i == values.length - 1) ? valueStr + values[i]
    					: valueStr + values[i] + ",";
    		}
    		params.put(name, valueStr);
    	}
    	
    	BasePay unionPay=BasePay.CreateNewWebPay("02", "", "");
    	unionPay.setParams(params);
    	
    	//获取订单返回参数信息
		jsonObject=unionPay.NotifyBackAppInfo();
		
		String code=jsonObject.getString("code");
		String message=jsonObject.getString("message");
		if(code.equals("1")){
			String orderID=jsonObject.getString("OrderNo");//原始订单号
			String PayAmount=jsonObject.getString("PayAmount");//金额 ，退货交易可能与原始订单金额不一致
			String qn=jsonObject.getString("qn");//查询交易号，后续退货需要用到，保存在订单表EXT_TXN_SEQ_ID 字段
			String settleAmount=jsonObject.getString("settleAmount");//金额 ，退货交易可能与原始订单金额不一致
			String respCode=jsonObject.getString("RespCode");//银联返回结果，00为成功
			String SettDate=jsonObject.getString("SettDate");//交易日期
			String respMsg=jsonObject.getString("respMsg");//银联返回消息，当返回状态不为00时该域有值
			String transType=jsonObject.getString("transType");//交易类型该值保存了原始交易类型，01：支付，04：退货，31：撤消
	
			//查询订单是否已支付成功
	    	Map formTxnMap = new HashMap();
			formTxnMap.put(ErpOrders.COL_ORDER_ID, orderID);
			SqlUtis.prepareSql(formTxnMap,SqlUtis.getSQL(formTxnMap, "a."+ ErpOrders.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ));
			ErpOrders orders = orpOrdersService.one(formTxnMap);
			

			//原始交易为订单支付
			if(transType.equals(Constants.UNION_TRANS_TYPE.TRANS_PAY)){
				
				Map formQueryTxnMap = new HashMap();
				formQueryTxnMap.put(ErpTxnSeq.COL_ORDER_ID, orderID);
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_STATE, "2");
				formQueryTxnMap.put(ErpTxnSeq.COL_TRN_TYPE, MAINFRAME_TYPE.BACK_PAY);//只有前台返回的报文中才有记录该支付流水号
				formQueryTxnMap.put(ErpTxnSeq.COL_TXN_TYPE, "00");//只有查询交易才会返回可用于退货的支付流水号
				
				SqlUtis.prepareSql(formQueryTxnMap,
						SqlUtis.getSQL(formQueryTxnMap, "a."+ ErpTxnSeq.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ),
						SqlUtis.getSQL(formQueryTxnMap, "a."+ ErpTxnSeq.COL_TXN_STATE,Types.VARCHAR,SqlUtis.EQ),
						SqlUtis.getSQL(formQueryTxnMap, "a."+ ErpTxnSeq.COL_TRN_TYPE,Types.VARCHAR,SqlUtis.EQ),
						SqlUtis.getSQL(formQueryTxnMap, "a."+ ErpTxnSeq.COL_TXN_TYPE,Types.VARCHAR,SqlUtis.EQ));
				
				ErpTxnSeq txnOldSeq = erpTxnSeqService.one(formQueryTxnMap);
				
				//只有在没有更新交易流水的情况下 才记录，保证交易流水的唯一
				if(txnOldSeq ==null || StringUtils.isEmpty(txnOldSeq.getExtTxnSeqId())){
					unionPayService.saveTxnInfo(orderID,Constants.TRANS_TYPE.GO_PAY,Constants.ONLINE_PAYMENT.UNION_PAY,Constants.MAINFRAME_TYPE.BACK_PAY,qn,Constants.TXN_STATE.TXN_O2,respCode,respMsg,Constants.PAY_CHANNEL.PAY_IOS);
				}
	    		if(orders.getOrderStatusId().equals(Constants.ERP_ORDER_STATUS.ORDER)){//表明订单已经支付成功了
	    			logger.info("********************WebPayAction notifyWebPayResult 银联手机支付后台通知，订单状态已更新，不处理********************");
	    		}else {
	    			if(respCode.equals("00")){
						orderService.payConfirmOrder(userId, orderID, Constants.ONLINE_PAYMENT.UNION_PAY, qn,Constants.PAY_CHANNEL.PAY_IOS);//保存银联返回的订单支付号，后续退货及撤消需要用到
		    			thirdBusinessService.callThirdService(orderID, userId);
		    			//支付成功后推送
		    			OrderService1.pushOrderByPayNo(orderID);
		    		}else{//订单支付失败，只记录交易流水信息
		    			unionPayService.saveTxnInfo(orderID,Constants.TRANS_TYPE.GO_PAY,Constants.ONLINE_PAYMENT.UNION_PAY,Constants.MAINFRAME_TYPE.BACK_PAY,qn,Constants.TXN_STATE.TXN_O1,respCode,respMsg,Constants.PAY_CHANNEL.PAY_IOS);
		    		}
	    		}
			}
			//原始交易为订单退货
			if(transType.equals(Constants.UNION_TRANS_TYPE.TRANS_REFUND)){
    			unionPayService.saveTxnInfo(orderID,Constants.TRANS_TYPE.PAY_BACK,Constants.ONLINE_PAYMENT.UNION_PAY,Constants.MAINFRAME_TYPE.BACK_PAY,qn,Constants.TXN_STATE.TXN_O2,respCode,respMsg,Constants.PAY_CHANNEL.PAY_IOS);

				//查询订单是否已退货成功，同时QN号有没有保存
				if(orders.getOrderStatusId().equals(Constants.ERP_ORDER_STATUS.CLOSED)){//表明订单已经退货成功了
	    			logger.info("********************WebPayAction notifyWebPayResult 银联手机支付后台通知，订单状态已更新，不处理********************");
	    		}else if(respCode.equals("00")){
	    			orderService.refund(userId, orderID);//保存银联返回的订单支付号，后续退货及撤消需要用到
	    		}else{//订单支付失败，只记录交易流水信息
	    			unionPayService.saveTxnInfo(orderID,Constants.TRANS_TYPE.PAY_BACK,Constants.ONLINE_PAYMENT.UNION_PAY,Constants.MAINFRAME_TYPE.BACK_PAY,qn,Constants.TXN_STATE.TXN_O1,respCode,respMsg,Constants.PAY_CHANNEL.PAY_IOS);
	    		}
			}
			//原始交易为订单撤消
			if(transType.equals(Constants.UNION_TRANS_TYPE.TRANS_CANCEL)){
    			unionPayService.saveTxnInfo(orderID,Constants.TRANS_TYPE.CANCEL,Constants.ONLINE_PAYMENT.UNION_PAY,Constants.MAINFRAME_TYPE.BACK_PAY,qn,Constants.TXN_STATE.TXN_O2,respCode,respMsg,Constants.PAY_CHANNEL.PAY_IOS);
				//查询订单是否已撤消成功，同时QN号有没有保存
				if(orders.getOrderStatusId().equals(Constants.ERP_ORDER_STATUS.CLOSED)){//表明订单已经撤消成功了
	    			logger.info("********************WebPayAction notifyWebPayResult 银联手机支付后台通知，订单状态已更新，不处理********************");
	    		}else if(respCode.equals("00")){
	    			orderService.payConfirmOrder(userId, orderID, Constants.ONLINE_PAYMENT.UNION_PAY, qn,Constants.PAY_CHANNEL.PAY_IOS);//保存银联返回的订单支付号，后续退货及撤消需要用到
	    		}else{//订单支付失败，只记录交易流水信息
	    			unionPayService.saveTxnInfo(orderID,Constants.TRANS_TYPE.CANCEL,Constants.ONLINE_PAYMENT.UNION_PAY,Constants.MAINFRAME_TYPE.BACK_PAY,qn,Constants.TXN_STATE.TXN_O1,respCode,respMsg,Constants.PAY_CHANNEL.PAY_IOS);
	    		}
			}
		}else{
			logger.info("********************WebPayAction notifyWebPayResult 银联手机支付后台通知消息处理失败，"+message+"********************");
		}
    	
    	logger.info("********************WebPayAction notifyWebPayResult end********************");
    }
    
    /**
	 * 获取银联支付结果
	 * @param orderId 订单编号
	 * @param orderTime 下单时间
	 * @param orderAmount 订单支付金额 
	 * @param channelCode 渠道代码 ，03:IOS，04:android
	 * @return
	 */
    public String getUnionPayResult(){
  
    	//先判断数据库中是否有完整的交易结果，如果有则直接返回，否则调用银联的查询接口
    	logger.info("********************WebPayAction getUnionPayResult Begin********************");  	
    	JSONObject jsonObject = new JSONObject();
        InputStream is;
        String userId=request.getParameter("userId");
        String orderId=request.getParameter("orderId");
        String orderTime=request.getParameter("orderTime");
        String orderAmount=request.getParameter("orderAmount");
        String channelCode=request.getParameter("channelCode");
        
        //得到客户端的请求交易数据：
        String source_text="orderId="+orderId+"&orderTime="+orderTime+"&orderAmount="+orderAmount+"&channelCode="+channelCode+"&userId="+userId;
        logger.info("得到的客户端原始交易请求数据："+source_text);
        this.validateSign(getLoginSign(),userId,orderId,orderTime,orderAmount,channelCode);
		//验证是否登录
		this.validateLoginApp();
		
        try {
        	//开始记录交易流水信息
        	//先根据订单号查询订单信息是否存在，然后再保存交易信息
        	Map formTxnMap = new HashMap();
    		formTxnMap.put(ErpOrders.COL_ORDER_ID, orderId);
    		SqlUtis.prepareSql(formTxnMap,SqlUtis.getSQL(formTxnMap, "a."+ ErpOrders.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ));
    		ErpOrders orders = orpOrdersService.one(formTxnMap);
        	//订单为待支付状态，说明没有发起支付，或者是支付后没有更新结果，再向银联发起查询请求
        	//开始记录交易流水信息
        	unionPayService.saveTxnInfo(orderId, Constants.TRANS_TYPE.QUERY, Constants.ONLINE_PAYMENT.UNION_PAY, Constants.MAINFRAME_TYPE.FRONT_PAY, "", TXN_STATE.TXN_O0,"","",channelCode);

    		BasePay unionPay=BasePay.CreateNewWebPay("02", orderId, orderAmount);
    		unionPay.setParameter("OrderTime", (new SimpleDateFormat("yyyyMMdd")).format(orders.getCreateTime()));
    		unionPay.setParameter("TransType", "01");
    		
    		jsonObject=unionPay.QueryResult();
    		String code=jsonObject.getString("code");
    		//保存得到的qn号
			String qn=jsonObject.getString("qn");
			unionPayService.saveTxnInfo(orderId, Constants.TRANS_TYPE.QUERY, Constants.ONLINE_PAYMENT.UNION_PAY, Constants.MAINFRAME_TYPE.FRONT_PAY, qn, TXN_STATE.TXN_O2,"","",channelCode);
			
    		if(code.equals("1")){//只有明确支付成功的才会更新订单状态
    			if(orders.getOrderStatusId().equals(Constants.ERP_ORDER_STATUS.PAY)){//当前的订单状没有更新，更新订单
        			orderService.payConfirmOrder(userId, orderId, Constants.ONLINE_PAYMENT.UNION_PAY, qn,Constants.PAY_CHANNEL.PAY_IOS);
        			thirdBusinessService.callThirdService(orderId, userId);
    			}
    		}else{
    			unionPayService.saveTxnInfo(orderId, Constants.TRANS_TYPE.QUERY, Constants.ONLINE_PAYMENT.UNION_PAY, Constants.MAINFRAME_TYPE.FRONT_PAY, "", TXN_STATE.TXN_O1,"","",channelCode);
    		}
            return this.writeJson(jsonObject);
        	
        }catch(Exception exc){
        	logger.info(exc.getMessage());
        	exc.printStackTrace();
        	jsonObject.put("code", "6");
    		jsonObject.put("message", exc.getMessage());
    		jsonObject.put("orderId", orderId);
        }
        logger.info("********************WebPayAction getUnionPayResult End********************");
        return this.writeJson(jsonObject);
    	
    }
  	/**
  	 * alipay退款异步结果返回
  	 * @return
  	 */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public String refundNotifyAlipayResult(){
		logger.info("********************WebPayAction notifyAlipayResult Begin********************");
		JSONObject jsonObject = new JSONObject();
		String userId = "system";

		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		Alipay alipay = (Alipay) BasePay.CreateNewWebPay("06", "", "");
		alipay.setParams(params);
		// 获取订单返回参数信息
		jsonObject = alipay.refundNotifyBackAppInfo();
		try {
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Expires", "0");
			response.setHeader("Pragma", "No-cache");
			
			response.setContentType("text/html;charset=UTF-8");
			
			response.getWriter().write("success");
			//this.response.getOutputStream().print("success");
			response.getWriter().flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
    
	
	/**
	 * 订单号生成，该生产订单号仅用于测试，商户根据自己需要生成订单号
	 * @return
	 */
	public static String generateOrdrNo(){
		DateFormat formater = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        StringBuilder sb = new StringBuilder(formater.format(new Date()));
        return sb.toString();
	}
}

